<template>
  <div>
    <div class="box">
      <div class="poetry-head">
        <div class="title">
          <span class="mui-icon mui-icon-search" v-show="showFlag" @click="goSearch"></span>
          <span class="mui-icon mui-icon-bars" v-show="searchFlag" @click="goList"></span>
        </div>
      </div>
      <div class="search-box" v-if="searchFlag">
        <div class="mui-input-row mui-input-search">
          <div class="search-input-box">
            <input
              type="search"
              class="mui-input-clear"
              @blur="getKey"
              ref="input"
              name="key"
              placeholder="请输入关键字(少于8个字)，选择诗歌类型"
              v-model="inputText"
            >
            <span class="mui-icon mui-icon-search"></span>
            <span class="mui-icon mui-icon-clear mui-hidden"></span>
          </div>
        </div>
        <div class="selection">
          <ul class="mui-table-view .mui-input-group">
            <li class="mui-table-view-cell mui-radio">
              <label for="num">
                诗体：
                <input v-model="checkedNum" type="radio" name="num" id="num" value="5">五言律诗
                <input v-model="checkedNum" type="radio" name="num" id="num" value="7">七言绝句
              </label>
            </li>
            <li class="mui-table-view-cell mui-radio">
              <label for="type">
                类型：
                <input v-model="checkedType" type="radio" name="type" id="type" value="1">藏头
                <input v-model="checkedType" type="radio" name="type" id="type" value="2">藏尾
                <input v-model="checkedType" type="radio" name="type" id="type" value="3">藏中
                <input v-model="checkedType" type="radio" name="type" id="type" value="4">递增
                <input v-model="checkedType" type="radio" name="type" id="type" value="5">递减
              </label>
            </li>
            <li class="mui-table-view-cell mui-radio">
              <label for="rhyme">
                押韵：
                <input v-model="checkedRhyme" type="radio" name="rhyme" id="rhyme" value="1">双句一押
                <input v-model="checkedRhyme" type="radio" name="rhyme" id="rhyme" value="2">双句押韵
                <input v-model="checkedRhyme" type="radio" name="rhyme" id="rhyme" value="3">一三四压
              </label>
            </li>
          </ul>
        </div>
        <div class="button">
          <mt-button type="primary" size="large" @click="submit">搜索</mt-button>
          <mt-button type="default" size="large" @click="reset">重置</mt-button>
        </div>
        <div class="history">
          <div class="cell-title">
            <span>搜索历史</span>
            <span class="mui-icon mui-icon-trash" @click="deleteSearchList"></span>
          </div>
          <div class="history-search">
            <span
              v-for="item in this.searchList"
              :key="item.key"
              @click="searchAgain(item)"
            >{{ item.key }}</span>
          </div>
        </div>
      </div>

      <div class="show-box" v-if="showFlag">
        <div v-for="item in list" :key="item.id" class="poetry-box">
          <!-- 有多种方式来渲染时，注意参数是否每次渲染都已被定义 -->
          <h4>{{ item.key }}</h4>
          <!-- 循环数组，key可以为索引值 -->
          <ul>
            <li v-for="(value,i) in item.poetry" :key="i">{{ value }}</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import "../../../lib/mui/css/mui.min.css";
import mui from "../../../lib/mui/js/mui.min.js";
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      placeholder: "输入内容按enter进行搜索",
      title: "藏头诗",
      showFlag: false,
      searchFlag: true,
      inputText: "",
      checkedNum: "",
      checkedType: "",
      checkedRhyme: "",
      numList: ["5", "7"],
      typeList: ["1", "2", "3", "4", "5"],
      rhymeList: ["1", "2", "3"],
      my_searchObj: {
        key: "春江花月夜",
        num: "5",
        type: "1",
        rhyme: "1"
      },
      list: [],
      searchList: [],
      dataURL: ""
    };
  },
  created() {
    this.showTitle(this.title);
    this.getSearchList();
    // this.getSearchResult(this.my_searchObj);
  },
  methods: {
    // 标题设置
    showTitle(title) {
      this.$emit("getTitle", title);
    },
    // 切换搜索页面
    goSearch() {
      this.showFlag = false;
      this.searchFlag = true;
    },
    // 切换结果页面
    goList() {
      this.showFlag = true;
      this.searchFlag = false;
      // 此处调一次该方法，不断的在调接口？？？？====================
      // this.getSearchResult(this.my_searchObj) ================
    },
    // 获取输入框文本内容并校验
    getKey() {
      // 获取input值的两种方法
      // var key = this.$refs.input.value.trim();
      var key = this.inputText.trim();
      // [\u4e00-\u9fa5] 正则匹配汉字
      var regex = /[^\u4e00-\u9fa5]/;
      if (this.my_searchObj.key.length == 0) return Toast("请输入关键字");
      if (this.my_searchObj.key.length > 8) return Toast("输入字数过长");
      if (regex.test(this.my_searchObj.key)) return Toast("只能输入汉字");
      // 判断是否重复输入搜索内容
      if (this.my_searchObj.key !== key) {
        this.my_searchObj.key = key;
      }
    },
    // 点击搜索进行校验，保存并进行搜索，切换到结果显示页面
    submit() {
      this.list = [];

      var selectNum = this.checkedNum;
      var selectType = this.checkedType;
      var selectRhyme = this.checkedRhyme;
      if (!selectNum && !selectType && !selectRhyme) {
        this.getAllItems();
        return;
      }
      if (!selectNum && !selectType) {
        this.getNumAndType(selectRhyme);
        return;
      }
      if (!selectNum && !selectRhyme) {
        this.getNumAndRhyme(selectType);
        return;
      }
      if (!selectType && !selectRhyme) {
        this.getTypeAndRhyme(selectNum);
        return;
      }
      if (!selectNum) {
        this.getAllNumItems(selectType, selectRhyme);
        return;
      }
      if (!selectType) {
        this.getAllTypeItems(selectNum, selectRhyme);
        return;
      }
      if (!selectRhyme) {
        this.getAllRhymeItems(selectNum, selectType);
        return;
      }
      this.my_searchObj.num = selectNum;
      this.my_searchObj.type = selectType;
      this.my_searchObj.rhyme = selectRhyme;

      // 变量不要与其他组件重名
      var historyObj = {};
      historyObj.key = this.my_searchObj.key;
      historyObj.num = selectNum;
      historyObj.type = selectType;
      historyObj.rhyme = selectRhyme;
      // 不能直接push this.my_searchObj，会把所有的内容都替换成最后一次的数据
      // this.searchList.push(this.my_searchObj) ========================
      // console.log(this.my_searchObj)
      this.getSearchResult(historyObj);
      this.searchList.push(historyObj);
      localStorage.setItem("searchList-key", JSON.stringify(this.searchList));
    },
    // 重置选项
    reset() {
      this.checkedNum = "";
      this.checkedType = "";
      this.checkedRhyme = "";
    },
    // 发送http请求获取结果
    getSearchResult(searchItem) {
      var url = "http://route.showapi.com/950-1";
      var data = {
        showapi_appid: "88927",
        showapi_sign: "7132f458c7df46c88cdd908f5346fb25",
        showapi_timestamp: this.getTimeStamp(),
        num: searchItem.num,
        type: searchItem.type,
        yayuntype: searchItem.rhyme,
        key: searchItem.key
      };
      // 序列化对象参数，否则获取失败
      this.$http
        .post(url, this.$qs.stringify(data))
        .then(res => {
          // console.log(res);
          var o = {};
          var date = new Date();
          var id = date + Math.floor(Math.random() * Math.pow(10, 8) + 1);
          o.key = searchItem.key;
          if (res.data.showapi_res_body.ret_code == 0) {
            var value = res.data.showapi_res_body.list;
            o.poetry = value.toString().split(",");
            // 用push,之前搜索的结果也会一致保存在搜索结果页面
            // 每次submit前先清空list再push,再此处清空，分类搜索也只会显示最后一次
            // this.list = [];
            this.list.push(o);
            // this.list =[o]
            // console.log(res.body.showapi_res_body.list);
            this.goList();
          } else {
            Toast("获取失败，请重试");
          }
        })
        .catch(err => {
          // console.log(err)
          // Toast(err);
          // return Promise.reject(err);
        });
    },
    // 获取时间戳，用于http请求
    getTimeStamp() {
      var date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      month = month < 10 ? "0" + month : month;
      var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      var minute =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      var second =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      var timeStamp = year + month + day + hour + minute + second;
      return timeStamp;
    },
    // 获取搜索历史列表
    getSearchList() {
      this.searchList =
        JSON.parse(localStorage.getItem("searchList-key")) || [];
    },
    // 清空搜索历史
    deleteSearchList() {
      localStorage.removeItem("searchList-key");
      this.searchList = [];
    },
    // 点击搜索记录进行再次搜索
    searchAgain(item) {
      this.list = [];
      this.getSearchResult(item);
      // console.log(item)
    },
    // todo: 搜索所有类型的藏头诗 2*5*3，不同组合搜索
    // 定义三个数组，嵌套遍历，生成搜索对象，发送请求获取数据并渲染
    getAllItems() {
      for (var i = 0; i < this.numList.length; i++) {
        for (var j = 0; j < this.typeList.length; j++) {
          for (var l = 0; l < this.rhymeList.length; l++) {
            this.my_searchObj.num = this.numList[i];
            this.my_searchObj.type = this.typeList[j];
            this.my_searchObj.rhyme = this.rhymeList[l];
            this.getSearchResult(this.my_searchObj);
          }
        }
      }
    },
    getAllNumItems(type, rhyme) {
      for (var i = 0; i < this.numList.length; i++) {
        this.my_searchObj.num = this.numList[i];
        this.my_searchObj.type = type;
        this.my_searchObj.rhyme = rhyme;
        this.getSearchResult(this.my_searchObj);
      }
    },
    getAllTypeItems(num, rhyme) {
      for (var i = 0; i < this.typeList.length; i++) {
        this.my_searchObj.type = this.typeList[i];
        this.my_searchObj.num = num;
        this.my_searchObj.rhyme = rhyme;
        this.getSearchResult(this.my_searchObj);
      }
    },
    getAllRhymeItems(num, type) {
      for (var i = 0; i < this.rhymeList.length; i++) {
        this.my_searchObj.rhyme = this.rhymeList[i];
        this.my_searchObj.num = num;
        this.my_searchObj.type = type;
        this.getSearchResult(this.my_searchObj);
      }
    },
    getTypeAndRhyme(num) {
      for (var j = 0; j < this.typeList.length; j++) {
        for (var l = 0; l < this.rhymeList.length; l++) {
          this.my_searchObj.num = num;
          this.my_searchObj.type = this.typeList[j];
          this.my_searchObj.rhyme = this.rhymeList[l];
          this.getSearchResult(this.my_searchObj);
        }
      }
    },
    getNumAndRhyme(type) {
      for (var i = 0; i < this.numList.length; i++) {
        for (var l = 0; l < this.rhymeList.length; l++) {
          this.my_searchObj.num = this.numList[i];
          this.my_searchObj.type = type;
          this.my_searchObj.rhyme = this.rhymeList[l];
          this.getSearchResult(this.my_searchObj);
        }
      }
    },
    getNumAndType(rhyme) {
      for (var i = 0; i < this.numList.length; i++) {
        for (var j = 0; j < this.typeList.length; j++) {
          this.my_searchObj.num = this.numList[i];
          this.my_searchObj.type = this.typeList[j];
          this.my_searchObj.rhyme = rhyme;
          this.getSearchResult(this.my_searchObj);
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
$baseColor: #26a2ff;
.box {
  .poetry-head {
    .title {
      span {
        position: fixed;
        right: 15px;
        top: 6px;
        z-index: 999;
        color: #fff;
      }
    }
    .mui-search {
      padding: 0 10px;
      input {
        background: #fff;
      }
    }
  }

  .search-box {
    margin-top: 20px;

    .mui-input-search,
    .mui-icon-bars {
      padding: 0 10px;
      .search-input-box {
        position: relative;
        input {
          margin: 0;
          padding-left: 28px;
        }
        .mui-icon-search {
          position: absolute;
          top: 50%;
          left: 5px;
          transform: translateY(-50%);
          font-size: 20px;
          color: #999;
        }
      }
    }

    .selection {
      margin-top: 20px;
      font-size: 16px;
      .mui-table-view {
        .mui-table-view-cell {
          padding: 10px 10px;
        }
        .mui-radio {
          label {
            padding-right: 0px;
            line-height: 1;
          }
          input {
            position: static;
            width: 22px;
            height: 22px;
            &::before {
              font-size: 20px;
            }
          }
        }
      }
    }

    .button {
      display: flex;
      flex-direction: row;
      margin: 10px;
      justify-content: space-between;
      .mint-button {
        flex: 49%;
        flex-grow: 0;
        font-size: 16px;
      }
    }

    .history {
      margin: 20px 10px;
      .cell-title {
        display: flex;
        justify-content: space-between;
        flex-direction: row;
        span {
          padding: 5px;
          color: #fff;
          background: $baseColor;
          border-radius: 5px;
          display: inline-block;
          &:last-of-type {
            background: none;
            color: #666;
          }
        }
      }
      .history-search {
        padding: 10px 0;
        span {
          padding: 5px;
          border-radius: 5px;
          background: rgba(0, 0, 0, 0.1);
          color: #666;
          display: inline-block;
          margin-bottom: 5px;
          margin-right: 5px;
        }
      }
    }
  }

  .show-box {
    margin-top: 30px;
    .poetry-box {
      position: relative;
      background: url("../../../static/images/bg.jpg") bottom left no-repeat;
      background-size: cover;
      margin: 0 10px;
      // border: 5px solid rgba(0, 0, 0, 0.6);
      border-radius: 10px;
      box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.3),
        -5px -5px 10px rgba(0, 0, 0, 0.3);

      h4 {
        writing-mode: vertical-lr;
        position: absolute;
        top: 40px;
        right: 20px;
      }
      ul {
        margin-bottom: 20px;
        text-align: center;
        border-radius: 10px;
        // 可能是设置了这个，手机上无法滑动
        // overflow: hidden;
        overflow-y: auto;
        padding: 40px 80px 150px 20px;

        li {
          list-style: none;
          padding: 10px 10px;
          writing-mode: vertical-lr;
          float: right;
          border-top: 2px solid #666;
          margin-top: 20px;
          background: rgba(255, 255, 255, 0.8);
          font-size: 16px;
        }
      }
    }
  }
}
</style>
